<template>
    <el-drawer v-model="isShow" :title="title" :destroy-on-close="true" size="50%" :close-on-press-escape="false"
        :close-on-click-modal="false" :show-close="false">
        <template #header="{ close, titleId, titleClass }">
            <h4 :id="titleId" :class="titleClass">{{ title }}</h4>
        </template>

        <el-form :model="form" label-width="auto" ref="formRef" :rules="rules">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="设备名称" required prop="servername">
                        <el-input v-model="form.servername" placeholder="请输入设备名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="设备编号" required prop="servercode">
                        <el-input v-model="form.servercode" placeholder="请输入设备编号" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="设备IP" required prop="serverip">
                        <el-input v-model="form.serverip" placeholder="请输入设备IP" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="用户名" required prop="serveruser">
                        <el-input v-model="form.serveruser" placeholder="请输入用户名" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="密码" required prop="serverpsw">
                        <el-input v-model="form.serverpsw" placeholder="请输入密码" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="端口号" required prop="serverport">
                        <el-input v-model="form.serverport" placeholder="请输入端口号" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <!-- <el-col :span="12">
                    <el-form-item label="域名IP" required prop="roomcode">
                        <el-input v-model="form.roomcode" placeholder="请输入域名IP" />
                    </el-form-item>
                </el-col> -->
                <el-col :span="12">
                    <el-form-item label="平台">
                        <el-input v-model="form.domainid" placeholder="请输入平台" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="设备类别" required prop="type">
                        <el-select v-model="form.type">
                            <el-option v-for="item in nj_device_type" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="所属单位" required prop="unitId">
                        <el-tree-select v-model="form.unitId" :data="deptOptions" default-expand-all
                            :props="{ value: 'deptId', label: 'deptName', children: 'children' }" value-key="deptId"
                            placeholder="选择上级部门" check-strictly @node-click="deptNameClick"
                            :disabled="isButtonDisabled" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <el-button type="primary" @click="submitHandle">提交</el-button>
            <el-button @click="isShow = false">关闭</el-button>
        </template>
    </el-drawer>
</template>

<script setup>
import { getCurrentInstance } from "vue";
import { createDevice, editDevice, getDeviceInfo } from "@/api/ParameterSetting/Device";
import { listDept, } from "@/api/system/dept";
import { getUserProfile } from "@/api/system/user";


const { proxy } = getCurrentInstance()
const { sys_normal_disable, nj_device_type } = proxy.useDict('sys_normal_disable', 'nj_device_type')
// 是否显示抽屉
const isShow = ref(false)
// 抽屉标题
const title = ref('')
// 部门
const department = ref([])
// 所属单位
const deptOptions = ref([]);


// 通知事件
const emit = defineEmits(['getDeviceList'])

const rules = {
    servercode: [{ required: true, message: "设备编号不能为空", trigger: "blur" }],
    servername: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
    unitId: [{ required: true, message: "所属单位不能为空", trigger: "blur" }],

    // roomtypeId: [{ required: true, message: "设备类别不能为空", trigger: "blur" }]
}

// 设备
const form = ref({})


const deptqueryParams = ref({})

const changeShowStatus = () => {
    isShow.value = !isShow.value
}

const isButtonDisabled = ref(false);

// 获取个人信息
const getUserInfo = async () => {
    await getUserProfile().then(res => {
        form.value.unitId = res.data.deptId
    })
}

// 添加设备
const showAddDrawer = (data_deptId) => {
    title.value = '添加设备';
    reset();
    getDepartment(data_deptId)


    changeShowStatus()
}

// 修改设备 
const showEditDrawer = async (data) => {
    title.value = '修改设备'
    isButtonDisabled.value = true;
    await getDeviceInfo(data.monitorserverId).then(res => {

        form.value = res.data
        form.value.unitId = Number(res.data.unitId)
        if (res.data.serverpsw.length > 0) {
            form.value.serverpsw = "******"
        }

        const Params = {
            unitId: form.value.unitId
        }


    })

    await listDept(deptqueryParams.value).then(res => {
        deptOptions.value = res.data.filter(
            item => item.isUnit === true
        );
        deptOptions.value = proxy.handleTree(deptOptions.value, "deptId");
    })

    changeShowStatus()
}
defineExpose({ showAddDrawer, showEditDrawer })




// 表格属性
const Areapaging = ref({
    pageNum: 1,// 页码
    pageSize: 9999// 分页数量
})




//获取单位（部门）列表
const getDepartment = async (data_deptId) => {
    if (data_deptId == "") {
        // getUserInfo();//找当前登录用户所在部门     
        isButtonDisabled.value = false;
    } else {
        form.value.unitId = data_deptId

        isButtonDisabled.value = true;
    }

    await listDept(deptqueryParams.value).then(res => {
        deptOptions.value = res.data.filter(
            item => item.isUnit === true
        );
        deptOptions.value = proxy.handleTree(deptOptions.value, "deptId");
    })
}

/** 节点单击事件 */
function deptNameClick(data) {
};

onMounted(() => {
    // getDepartment()
    getUserInfo()
    // console.log('1');
})
const submitHandle = () => {
    // 必输校验--标签<el-form :model="form" label-width="auto" ref="formRef"  :rules="rules"> 添加ref="formRef" 属性 :rules="rules"绑定
    // 然后const rules = {里面是需要的rules}   在每个<el-form-item label="设备编号" required prop="对应字段">加上 prop="对应的字段"
    // submitHandle的时候先判断    proxy.$refs["formRef"].validate(valid => {
    // if (valid) {  valid true面执行具体代码逻辑     });}

    var str = form.value.serverpsw;
    if (str !== "******") {
        if (str.includes('*')) {
            proxy.$modal.msgError(`密码不能包含*`)
            return false
        }
        else {
         
        }
    }   
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
            if (form.value['monitorserverId']) {
                editDevice(form.value).then(res => {
                    changeShowStatus()
                    emit('getDeviceList', '来了老弟')
                })
            } else {
                createDevice(form.value).then(res => {
                    changeShowStatus()
                    emit('getDeviceList', '来了老弟')
                })
            }
        }

    });
}

// 关闭后的回调事件
const closeHandle = () => {
    form.value = defaultQuery
}
/** 重置操作表单 */
function reset() {
    form.value = {
        roomname: undefined,
        roomcode: undefined,
        roomtypeId: undefined,
        unitId: undefined,

        state: '0',
    };
    proxy.resetForm("formRef");
};
/** 取消按钮 */
const cancel = () => {
    isShow.value = false
    reset();
}

</script>

<style lang="scss" scoped>
h4 {
    margin: 10px 0;
}
</style>